import api from './api'

function getPagServer(url, idx, opt, _this, callBack) { //公共分页 
  _this.setData({
    hasMore: true //当进来数据最下面显示‘玩了命的加载中’
  })
  api.$get(url, opt).then((data) => {
    if (data.errcode == 0) {
      if (data.list && data.list.length > 0) {
        _this.setData({
          ['pageList' + idx]: _this.data['pageList' + idx].concat(data.list), //当前某个更新数据
          ['page' + idx]: _this.data['page' + idx] + 1, //当前某个更新页码
          ['isLodingLock' + idx]: true, // 当前某个锁关闭 
          hasMore: false,
        });
      } else {
        _this.setData({
          hasMore: false //当加载完所有数据最下面显示‘没有跟多数据了’
        })
      }
      callBack && callBack(data)
    } else if (data.errcode == 202) {
      //后返回的 错误提示
      wx.showToast({
        title: data.errmsg,
        icon: 'none',
        duration: 2000
      })
    };

  });
}

const authorize = (setting) => () => { // 重复获取权限操作
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: (response) => {
        if (!response.authSetting[setting] && response.authSetting[setting] !== undefined) { //如果用户没有 允许相关权限再次提示重新询问开启相关权限
          wx.showModal({
            title: '提示',
            content: '使用此功能请先在小程序设置中授权',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success(tag) {
                    if (tag.authSetting[setting]) { // 用户在设置页选择同意授权
                      resolve(true)
                    }
                  }
                });
              } else if (res.cancel) {
                //resolve(false)
              }
            }
          })
        } else {
          resolve(true)
        }

      }
    })
  })
}

const authUserLocation = authorize('scope.userLocation') //开启位置权限


function getPageList(api, _this, url, params, lastId, id = 'id') { 
  return new Promise((resolve, reject) => {
    _this.setData({
      hasMore: true //当进来数据最下面显示‘玩了命的加载中’
    })

    if (lastId == 0) {
      _this.setData({
        pageList: []
      })
    } 
    api.$post(url, params).then((res) => { //分页 
      console.log(res)
      if (res.pageList.length > 0) {
        _this.setData({
          pageList: _this.data.pageList.concat(res.pageList), //当前某个更新数据 
          lastId: res.pageList[res.pageList.length - 1][id],
          isLodingLock: true, // 当前某个锁关闭 
          hasMore: false,
        });
      } else {
        _this.setData({
          hasMore: false //当加载完所有数据最下面显示‘没有跟多数据了’
        })
      }
      if (_this.data.pageList.length == 0) {
        _this.setData({
          isKongList: true,
        })
      }
      resolve(_this.data.pageList)
    });
  })
}


module.exports = {
  getPagServer,
  authUserLocation, 
  getPageList
}